package com.cloudcc.boot.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class BigDecimal3DigitsAsStringSerializer extends JsonSerializer<BigDecimal> {

    private static final ThreadLocal<DecimalFormat> DF =
            ThreadLocal.withInitial(() -> {
                DecimalFormat df = new DecimalFormat("0.000");
                df.setRoundingMode(RoundingMode.DOWN);
                return df;
            });

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
            return;
        }
        gen.writeString(DF.get().format(value));
    }
}